
package edu.uoc.tdp.client.estudiants;

import edu.uoc.tdp.beans.conexio.Estudiant;
import edu.uoc.tdp.beans.proves.Prova;
import edu.uoc.tdp.common.RemotEstudiantsInterface;
import edu.uoc.tdp.common.TDSLanguageUtils;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.WindowConstants;
import javax.swing.table.DefaultTableModel;

/**
 * Pantalla que consulta i mostra les proves disponibles per a inscriure's.
 * Marca les proves a les que ja estas inscrit amb un chekbox
 * @author Jordi
 */
public class PantallaConsultaProves extends JFrame{
    
    private RemotEstudiantsInterface remot;
    private Estudiant estudiant;
    private List<Prova> entrada = new ArrayList<Prova>();

    /**
     * Constructor amb dos paràmetres   
     * @param pEsrudiant           Identificador de l'estudiant actual
     * @param pRemot               Remot que ens permet connectar amb el servidor
     */
   public PantallaConsultaProves(Estudiant pEstudiant,RemotEstudiantsInterface pRemot){
        estudiant = pEstudiant;
        remot = pRemot;
        
        setTitle(TDSLanguageUtils.getMessage("titol.Client")); 

        initComponents();
        carregainicial();
        
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        addWindowListener(new java.awt.event.WindowAdapter() {            
            public void windowClosing(java.awt.event.WindowEvent evt) {
                tancarFinestra(evt);
            }
        });
    }    

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable();
        jButton1 = new javax.swing.JButton();
        jButton2 = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jLabel1.setFont(new java.awt.Font("Tahoma", 0, 14));
        jLabel1.setForeground(new java.awt.Color(0, 0, 255));

        jTable1.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null, null, null, null},
                {null, null, null, null, null, null, null},
                {null, null, null, null, null, null, null},
                {null, null, null, null, null, null, null}
            },
            new String [] {
                "Título 1", "Título 2", "Título 3", "Título 4", "Título 5", "Título 6", "Título 7"
            }
        ) {
            boolean[] canEdit = new boolean [] {
                false, false, false, false, false, false, false
            };

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        jScrollPane1.setViewportView(jTable1);

        jButton1.setText("Veure Prova");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jButton2.setText("Tornar");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addComponent(jButton1)
                        .addGap(27, 27, 27)
                        .addComponent(jButton2))
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 749, Short.MAX_VALUE)
                    .addComponent(jLabel1))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(34, 34, 34)
                .addComponent(jLabel1)
                .addGap(18, 18, 18)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 220, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jButton1)
                    .addComponent(jButton2))
                .addContainerGap(42, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

     /**
     * Agafa la prova seleccionada i obre la pantalla PantallaDetall per a mostrar
     * el detall de la prova.
     * @param evt               disparador
     */
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
       Prova prova = new Prova();
        if (jTable1.getSelectedRow() == -1){
            JOptionPane.showMessageDialog 
             (null, "CAP FILA SELECCIONADA", "ATENCIO", JOptionPane.WARNING_MESSAGE);
        } else {
            
            prova = entrada.get(jTable1.getSelectedRow());
        
            new PantallaDetall(prova,estudiant,remot).setVisible(true); 
            this.dispose();
          }
}//GEN-LAST:event_jButton1ActionPerformed

     /**
     * Tanca la finestra
     * @param evt               disparador
     */
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
       tancarFinestraboto(evt);
}//GEN-LAST:event_jButton2ActionPerformed

     /**
     * Fa la primera carrega de la pantalla. Posant el valor a els elements de texte i fent la carrega
     * de les proves en estat inscripcio     
     */
    private void carregainicial(){
         try {
           
            TDSLanguageUtils.setDefaultLanguage("edu/uoc/tdp/i18n/messages");
            Prova prova = new Prova();
            
            this.setTitle(TDSLanguageUtils.getMessage("estudiants.pantalla.consultaproves.nom"));
            
            entrada = remot.ObtenirProves();
            jLabel1.setText(TDSLanguageUtils.getMessage("estudiants.pantalla.consultaproves.title"));
            jButton1.setText(TDSLanguageUtils.getMessage("estudiants.pantalla.consultaproves.Button.veure"));
            jButton2.setText(TDSLanguageUtils.getMessage("estudiants.pantalla.consultaproves.Button.tornar"));
            
            DefaultTableModel modelo = new DefaultTableModel()
            
            {
            @Override
                public Class getColumnClass(int columnIndex) {
                  if (columnIndex == 6) {
                        return Boolean.class;
                    } else {
                        return super.getColumnClass(columnIndex);
                  }
                }
                @Override
                public boolean isCellEditable(int rowIndex, int columnIndex) {
                return false;
                }
            };
            
            modelo.addColumn(TDSLanguageUtils.getMessage("estudiants.pantalla.consultaproves.col1"));
            modelo.addColumn(TDSLanguageUtils.getMessage("estudiants.pantalla.consultaproves.col2"));
            modelo.addColumn(TDSLanguageUtils.getMessage("estudiants.pantalla.consultaproves.col3"));
            modelo.addColumn(TDSLanguageUtils.getMessage("estudiants.pantalla.consultaproves.col4"));
            modelo.addColumn(TDSLanguageUtils.getMessage("estudiants.pantalla.consultaproves.col5"));
            modelo.addColumn(TDSLanguageUtils.getMessage("estudiants.pantalla.consultaproves.col6"));
            modelo.addColumn("Inscrit");
            
            
            for (int i = 0;i<entrada.size();i++) { 
 
                prova = entrada.get(i);
                
                Object[] fila = new Object[7];
                fila[0] = prova.getDescripcio();
                String tipusronda = tipusderonda(prova);
                if(tipusronda.equals("F")){
                    fila[1] = "FINAL";
                    fila[2] = prova.getRondaFinal().getNombrePreguntes();
                } else {
                    fila[1] = "ELIMINATORIA";
                    fila[2] = prova.getRondaEliminatoria().getNombrePreguntes();
                }
                 
                fila[3] = prova.getNombrePlaces();  
                fila[4] = prova.getNombrePlaces() - prova.getNombreInscrits();  
                fila[5] = prova.getDataFiInscripcio();
                fila[6] = remot.ComprovaInscripcio(prova.getIdProva(), estudiant.getIdIntern());
               
                
                modelo.addRow(fila); 
            } 
            this.jTable1.setModel(modelo); 
                                    
        } catch (Exception e) {
             JOptionPane.showMessageDialog 
             (null, e.getMessage(), TDSLanguageUtils.getMessage("estudiants.common.error.literalerror"), JOptionPane.ERROR_MESSAGE);
        }
    }

     /**
     * Tancament de la finestra des de d'un windowevent
     */
    private void tancarFinestra(java.awt.event.WindowEvent evt) {
        dispose();
        System.exit(0);
    }
    
    /**
     * Tancament de la finestra des des del boto tancar
     */    
    private void tancarFinestraboto (java.awt.event.ActionEvent evt) {
        dispose();
    }
 
     /**
     * Retorna el tipus de ronda en que s'inscriurà l'estudiant per aquella prova
     * @return String     Tipus de ronda
     */  
    private String tipusderonda(Prova prova) {
        
        String sortida = "";
        
        if (prova.getRondaEliminatoria() == null){
            sortida = "F";
        } else {
                sortida = "E";
          } 
        return sortida;
    }    
 
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable jTable1;
    // End of variables declaration//GEN-END:variables
}
